<template>
  <el-select
    v-model="selectedIds"
    placeholder="请选择人员分类"
    clearable
    multiple
  >
    <el-option
      v-for="group in groups"
      :key="group.id"
      :label="group.name"
      :value="group.id"
    />
  </el-select>
</template>

<script lang="ts" setup>
import { computed, ref, onMounted, watch } from 'vue'
import type { PropType } from 'vue'
import * as GroupApi from '@/api/member/group'

defineOptions({ name: 'MemberGroupMultipleSelect' })

const props = defineProps({
  /** 下拉框选中值 **/
  modelValue: {
    type: Array as PropType<number[]>,
    default: () => []
  }
})

const emit = defineEmits({
  // 更新选中IDs
  'update:modelValue': (value: number[]) => true,
  // 新增事件：传递选中的名称
  'update:names': (value: string) => true
})

const groups = ref<GroupApi.GroupVO[]>([])
const selectedIds = ref<number[]>(props.modelValue || [])

// 计算选中的名称（逗号分隔）
const selectedNames = computed(() => {
  return selectedIds.value
    .map(id => {
      const group = groups.value.find(g => g.id === id)
      return group?.name || ''
    })
    .filter(name => name)
    .join(', ')
})

// 监听选中值变化
watch(selectedIds, (newVal) => {
  emit('update:modelValue', newVal)
  emit('update:names', selectedNames.value)
}, { deep: true })

// 监听外部值变化（用于回显）
watch(() => props.modelValue, (newVal) => {
  if (JSON.stringify(newVal) !== JSON.stringify(selectedIds.value)) {
    selectedIds.value = newVal || []
  }
})

// 获取分类列表
const getList = async () => {
  groups.value = await GroupApi.getSimpleGroupList()
  console.log('groups===>', groups);
  // 初始触发一次名称更新
  emit('update:names', selectedNames.value)
}

onMounted(() => {
  console.log('组件挂载')
  getList()
})
</script>
